<?php

namespace Lims\InquiryBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Utils\SecurityBundle\CustomClass\SecurityFunctions;
use Symfony\Component\HttpFoundation\Response;

class InquiryController extends Controller
{
    
    private $isLegalEntity;

    public function searchAction()
    {
        $user = $this->checkIsLoggedIn();
        return $this->render('LimsInquiryBundle:Inquiry:search.html.twig', array());
    }
    
    public function findByRegisterNumberAction()
    {
        if(isset($_POST['registerNumber']))
        {
            $registerNumber = SecurityFunctions::clear($_POST['registerNumber']); 
            $credit = $this->getDoctrine()->getManager()->getRepository('LimsMainBundle:Credit')->findHasInquiry($registerNumber);
            if($credit)
            {
                $result = array('status' => 'success', 'data' => $credit);
            }else{
                $result = array('status' => 'error', 'msg' => 'Зээлийн мэдээлэл олдсонгүй.');
            }
            
            $response = new Response(json_encode($result));
            $response->headers->set('Content-Type', 'application/json');
            return $response;
            
        }else{
            $response = new Response(json_encode(array('status' => 'error', 'msg' => 'Регистрийн дугаар оруулана уу!')));
            $response->headers->set('Content-Type', 'application/json');
            return $response;
        }
    }
    
    public function showAction()
    {
        $registerNumber = SecurityFunctions::clear($_POST['registerNumber']);        
        $today = date('Y-m-d');
        $inquiry = $this->createInquiry($registerNumber);
//        var_dump($inquiry);die;
        if($this->isLegalEntity == 0)
        {
            
            return $this->render('LimsInquiryBundle:Inquiry:inquiryCitizen.html.twig', array(
                'date' => $today,
                'year' => date('Y'),
                'month' => date('m'),
                'day' => date('d'),
                'inquiry' =>$inquiry
                ));
        }else{
            return $this->render('LimsInquiryBundle:Inquiry:inquiryLegalEntity.html.twig', array());
        }
        
    }

    private function createInquiry($registerNumber)
    {
        $inquiry = array();
        $em = $this->get('doctrine')->getManager();
        $isLegalEntity = $this->getDoctrine()->getManager()->getRepository('LimsMainBundle:Debtor')->checkIsLegalEntity($registerNumber);
        
        if($isLegalEntity == 0){
            $this->isLegalEntity = 0;
            $inquiry['debtor'] = $em->getRepository('LimsMainBundle:Debtor')->createInquiryByRegisterNumber($registerNumber);
            $inquiry['contact'] = $em->getRepository('LimsMainBundle:Debtor')->getDebtorContact($registerNumber);
            $inquiry['job'] = $em->getRepository('LimsMainBundle:Job')->createInquiryByRegisterNumber($registerNumber);
        }else{
            $this->isLegalEntity = 1;
            $inquiry['debtor'] = $em->getRepository('LimsMainBundle:Debtor')->createInquiryByRegisterNumber($registerNumber);
//            $inquiry['contact'] = $this->getDoctrine()->getManager()->getRepository('LimsMainBundle:LegalEntityContact')->createInquiryByRegisterNumber($registerNumber);
            $inquiry['job'] = null;
        }
        
        // credit information
        $inquiry['credit'] = $this->getCredit($registerNumber);        
        
        // installment information
        foreach($inquiry['credit'] AS $k => $credit ){            
            $inquiry['schedule'][$k] = $this->getSchedule($credit['ID']);
        }

        // payment information
        foreach($inquiry['credit'] AS $k => $credit ){            
            $inquiry['payment'][$k] = $this->getPayment($credit['ID']);
        }

//        // partner information
//        $inquiry['partner'] = $this->getPartner($registerNumber);
        
        return $inquiry;
        
    }
    
    private function getCredit($registerNumber)
    {
        $em = $this->getDoctrine()->getManager();        
        $credit = $em->getRepository('LimsMainBundle:Credit')->createInquiry($registerNumber);        
        return $credit;
    }
    
    private function getSchedule($creditId)
    {
        $em = $this->getDoctrine()->getManager();
        $schedule = $em->getRepository('LimsMainBundle:CreditSchedule')->getScheduleForInquiry($creditId);
        return $schedule;
    }
    
    private function getPayment($creditId)
    {
        $payment = $this->getDoctrine()->getManager()->getRepository('LimsMainBundle:Payment')->getPaymentForInquiry($creditId);
        return $payment;
    }
    
    private function getPartner($registerNumber)
    {
        $partner = $this->getDoctrine()->getManager()->getRepository('LimsMainBundle:Partner')->createPartner($registerNumber);
        return null;
    }
    
    private function checkIsLoggedIn()
    {
		if('anon.' == $this->container->get('security.context')->getToken()->getUser())
		{
			header("Location: /exit/");
		}
		
        if($this->container->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY') === FALSE)
        {
            header("Location: /exit/");
        }else{
            return $this->container->get('security.context')->getToken()->getUser();
        }
    }
}
